package com.guoji.cameracall.helper

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface
import java.io.IOException

/**
 * create by zhongZihao on 2021/9/27
 * 拉流解码
 */
class DecodeLiveH265 {
    private var mediaCodec: MediaCodec? = null

    fun initDecoder(surface: Surface) {
        try {
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_HEVC)
            val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, 1080, 1920)
            format.setInteger(MediaFormat.KEY_BIT_RATE, 1080 * 1920)
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 15)
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5)
            mediaCodec!!.configure(
                format,
                surface,
                null, 0
            )
            mediaCodec!!.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }



    fun callback(data: ByteArray?) {
        data ?: return
        mediaCodec ?: return
        Log.i("TAG", "EncodePushH265 接收到消息: " + data.size)
        val index = mediaCodec!!.dequeueInputBuffer(10000)
        if (index>0){
            val inputBuffer = mediaCodec!!.getInputBuffer(index)
            inputBuffer?.clear()
            inputBuffer?.put(data, 0, data.size)
            mediaCodec!!.queueInputBuffer(index,0,data.size,System.currentTimeMillis(),0)
        }
        val bufferInfo = MediaCodec.BufferInfo()
        var outIndex = mediaCodec!!.dequeueOutputBuffer(bufferInfo, 100000)
        while (outIndex>0){
            mediaCodec!!.releaseOutputBuffer(outIndex, true)
            outIndex = mediaCodec!!.dequeueOutputBuffer(bufferInfo, 0)
        }

    }

    fun release(){
        mediaCodec?.release()
    }
}